package com.cyou.qb.admin.web;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.cyou.fz173.util.JacksonUtil;
import com.cyou.nad.datastore.query.JdbcPage;
import com.cyou.nad.tag.table.TransCol;
import com.cyou.nad.utils.RequestUtils;
import com.cyou.qb.common.domain.Active;
import com.cyou.qb.common.domain.ActiveRule;
import com.cyou.qb.common.domain.JiuGongGeEx;
import com.cyou.qb.common.domain.QiangbaAdmin;
import com.cyou.qb.common.domain.WinnerEx;
import com.cyou.qb.common.service.ActivityService;
import com.cyou.qb.common.service.ConfigDisService;
import com.cyou.qb.common.service.NameValueService;
import com.cyou.qb.common.service.WinnerService;
import com.cyou.qb.constants.CodeTransConstants;
import com.cyou.qb.constants.Constants;
import com.cyou.qb.face.entity.ActivityInfo;
import com.cyou.qb.face.entity.GameInfo;
import com.cyou.qb.face.entity.NameValue;
import com.cyou.qb.face.entity.VideoInfo;
import com.cyou.qb.face.entity.trans.ActReturn;
import com.cyou.qb.face.exception.QbGetDataException;
import com.cyou.qb.face.service.GetGameInfoService;
import com.cyou.qb.face.service.QbOperateService;
import com.cyou.qb.service.UploadService;

@Controller
@RequestMapping(value = "/activity")
public class ActivityController extends BaseController {
	//service

	@Resource(name = "ActivityServiceCacheImpl")
	private ActivityService activityService;
	@Resource(name = "NameValueServiceImpl")
	private NameValueService nameValueService;
	@Resource(name = "QbOperateImpl")
	private QbOperateService qbOperateService;
	@Autowired
	private UploadService uploadService;

	@Resource(name = "WinnerServiceCacheImpl")
	private WinnerService winnerService;
	@Resource(name = "ConfigDisServiceCacheImpl")
	private ConfigDisService configDisService;
	@Resource(name = "QbGameImpl")
	private GetGameInfoService gameInfoService;


	/**
	 * 活动预览功能
	 * 
	 * @author wangwenlong
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws Exception 
	 * @throws NumberFormatException 
	 */
	@RequestMapping(value = "/preview")
	public String activityPreview(HttpServletRequest request, HttpServletResponse response, Model model)
			throws NumberFormatException, Exception {
		String activeId = request.getParameter("activeId");
		Assert.hasText(activeId, "活动不能为空");
		Assert.isTrue(NumberUtils.isDigits(activeId));
		Active active = activityService.findActivity(Integer.parseInt(activeId));
		Assert.notNull(active, "活动不存在");

		String gameCode = active.getGameCode();
		Assert.hasText(gameCode, "游戏数据不能为空");
		boolean flag = activityService.checkPreview(Integer.parseInt(activeId));
		List<JiuGongGeEx> jiuGongGeExList = configDisService.findJiuGongGeExByActId(Integer.parseInt(activeId));

		jiuGongGeExList = JiuGongGeEx.fillEmptyPosition(jiuGongGeExList, Integer.parseInt(activeId));

		Assert.isTrue(jiuGongGeExList.size() == 8);
		List<WinnerEx> topWinnerList = winnerService.findTopWinnerByActive(Integer.parseInt(activeId),
				Constants.TOP_WINNER_SIZE);

		String rule = active.getRule();
		if (rule == null)
			rule = "[]";
		List<ActiveRule> ruleList = JacksonUtil.toCollection(rule, ArrayList.class, ActiveRule.class);
		int gCost = 0;
		for (ActiveRule activeRule : ruleList) {
			if (activeRule.getType().equals("4")) {
				gCost = activeRule.getValue();
			}
		}
		List<VideoInfo> videoInfoList = gameInfoService.getGameVideoInfo(gameCode);
		List<NameValue> gameNews = gameInfoService.getGameNews(gameCode);
		GameInfo frontGameInfo = gameInfoService.getFrontGameInfo(gameCode);

		model.addAttribute(active);
		model.addAttribute("ruleList", ruleList);
		model.addAttribute("videoInfoList", videoInfoList);
		model.addAttribute("gameNews", gameNews);
		model.addAttribute("gCost", gCost);
		model.addAttribute(frontGameInfo);

		model.addAttribute("topWinnerList", topWinnerList);
		int i = 0;
		for (JiuGongGeEx obj : jiuGongGeExList) {
			model.addAttribute("jiuGongGeEx" + i, obj);
			i++;
		}
		return "preview/previewPlay";
	}

	/**
	 * 
	 * Description 活动列表页
	 * @author lidongwei
	 * @throws IOException 
	 * @since 2012-10-6
	 */
	@RequestMapping(value = "/index")
	public String index(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
		try {
			//获取页面约束条件
			String activityType = StringUtils.trimToEmpty(request.getParameter("activityType"));
			String activityName = StringUtils.trimToEmpty(request.getParameter("activityName"));
			String stateStr = StringUtils.trimToEmpty(request.getParameter("status"));
			//从数据库中查询数据
			//获取登录信息
			QiangbaAdmin admin = (QiangbaAdmin) request.getSession().getAttribute("loginedUser");
			Assert.notNull(admin, "活动添加人为空，请重新登录或联系管理员");
			JdbcPage page = activityService.findPageQueryActivity(admin, stateStr, activityType, activityName,
					getPageNo(), getPageSize(DEFAULT_PAGE_SIZE));
			model.addAttribute("page", page);
			//填充相对应的文字
			List<TransCol> trans = new ArrayList<TransCol>(2);
			trans.add(new TransCol("status", CodeTransConstants.ACTIVITY_STATUS));
			trans.add(new TransCol("faceStatus", CodeTransConstants.ACTIVITY_FACESTATUS));
			model.addAttribute("trans", trans);
			ResourceBundle bundle = ResourceBundle.getBundle("system");
			String jsURL = bundle.getString("fragment.jsURL");
			String cssURL = bundle.getString("fragment.cssURL");
			model.addAttribute("jsURL", jsURL);
			model.addAttribute("cssURL", cssURL);
			//将request中的数据存储
			saveAllParameters(request);
			return "activity/activitylist";
		} catch (Exception e) {
			log.error("添加活动出错", e);
			print(response, "error:" + e.getMessage());
			return "activity/activitylist";
		}
	}

	/**
	 * 
	 * Description 跳转到添加活动页面
	 * @author lidongwei
	 * @since 2012-10-6
	 */

	@RequestMapping(value = "/toSavePage")
	public String toSavePage(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
		//获取从游戏列表和游戏类别列表
		List<NameValue> gameNameList = nameValueService.findNameValue(1);
		List<NameValue> gameTypeList = nameValueService.findNameValue(2);
		//存储到request中
		request.setAttribute("gameNameList", gameNameList);
		request.setAttribute("gameTypeList", gameTypeList);
		return "activity/addactivity";
	}

	/**
	 * 
	 * Description 保存一个活动
	 * @author lidongwei
	 * @since 2012-10-6
	 */
	@RequestMapping(value = "/saveActivity")
	public String saveActivity(Model model, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try {
			//获取行页面传来的信息
			String activeNmae = StringUtils.trimToEmpty(request.getParameter("activeName"));
			String gameCode = StringUtils.trimToEmpty(request.getParameter("gameCode"));
			String gameType = StringUtils.trimToEmpty(request.getParameter("gameType"));
			String gameComOp = StringUtils.trimToEmpty(request.getParameter("gameComOp")); 
			String gameComRd = StringUtils.trimToEmpty(request.getParameter("gameComRd"));
			String gameNet = StringUtils.trimToEmpty(request.getParameter("gameNet"));
			
			String gameChannel = StringUtils.trimToEmpty(request.getParameter("gameChannel"));
			String gameBBS = StringUtils.trimToEmpty(request.getParameter("gameBBS"));
			String gameDown = StringUtils.trimToEmpty(request.getParameter("gameDown"));
			String image1Url = StringUtils.trimToEmpty(request.getParameter("image1Url"));
			String image2Url = StringUtils.trimToEmpty(request.getParameter("image2Url"));
			String image2Link = StringUtils.trimToEmpty(request.getParameter("image2Link"));
			String startDate = StringUtils.trimToEmpty(request.getParameter("startDate"));
			String startHour = StringUtils.trimToEmpty(request.getParameter("startHour"));
			String endDate = StringUtils.trimToEmpty(request.getParameter("endDate"));
			String endHour = StringUtils.trimToEmpty(request.getParameter("endHour"));
			String memo = StringUtils.trimToEmpty(request.getParameter("memo"));
			String introduce = StringUtils.trimToEmpty(request.getParameter("introduceHtml"));
			//获取当前添加活动的人
			QiangbaAdmin admin = (QiangbaAdmin) request.getSession().getAttribute("loginedUser");

			String rule1Type = request.getParameter("baseinfo1Radio");
			String rule1Value = request.getParameter("baseinfo1Input");
			String rule1Memo = request.getParameter("baseinfo1Text");
			//断言进行判空：
			Assert.hasText(gameCode, "未获取gamecode");
			Assert.hasText(image1Url, "不能获取上传文件地址");
			Assert.hasText(image2Url, "不能获取上传文件地址");
			Assert.hasText(image2Link, "图片链接不能为空");
			Assert.hasText(startDate, "开始日期不能为空");
			Assert.hasText(startHour, "开始时间不能为不能为空");
			Assert.hasText(endDate, "结束日期不能为不能为空");
			Assert.hasText(endHour, "结束时间不能为不能为空");
			Assert.hasText(memo, "活动描述不能为不能为空");
			Assert.hasText(introduce, "活动介绍不能为不能为空");
			Assert.notNull(admin, "活动添加人为空，请重新登录或联系管理员");

			//下面可为空
			String rule2Type = request.getParameter("baseinfo2Radio");
			String rule2Value = request.getParameter("baseinfo2Input");
			String rule2Memo = request.getParameter("baseinfo2Text");
			String rule3Type = request.getParameter("baseinfo3Radio");
			String rule3Value = request.getParameter("baseinfo3Input");
			String rule3Memo = request.getParameter("baseinfo3Text");
			//处理活动参与规则
			List<ActiveRule> arList = new ArrayList<ActiveRule>();

			//允许不勾选radio
			if (rule1Type != null && rule1Type.length() != 0) {
				ActiveRule activeRule1 = new ActiveRule();
				activeRule1.setType(rule1Type);
				activeRule1.setMemo(rule1Memo);
				activeRule1.setValue(Integer.valueOf(rule1Value));
				arList.add(activeRule1);
			}
			if (rule2Type != null && rule2Type.length() != 0) {
				ActiveRule activeRule2 = new ActiveRule();
				activeRule2.setType(rule2Type);
				activeRule2.setMemo(rule2Memo);
				activeRule2.setValue(Integer.valueOf(rule2Value));
				arList.add(activeRule2);
			}
			if (rule3Type != null && rule3Type.length() != 0) {
				ActiveRule activeRule3 = new ActiveRule();
				activeRule3.setType(rule3Type);
				activeRule3.setMemo(rule3Memo);
				activeRule3.setValue(Integer.valueOf(rule3Value));
				arList.add(activeRule3);
			}
			String rule = JacksonUtil.toJson(arList);
			int adminId = admin.getAdminId();

			//将从前台获取的非格式化的时间格式化
			String startTime = getDateStr(startDate, startHour);
			String endTime = getDateStr(endDate, endHour);
			//处理gamecode、gameType
			String gameNmae = "";
			if (gameCode != null) {
				gameNmae = nameValueService.findGameNameByGameCode(gameCode);//根据gamecode获取gamename
			}
			if ("null".equals(gameType)) {
				gameType = "无";
			}
			//写入数据库
			activityService.saveOneActivity(activeNmae, gameCode, gameNmae, gameType, gameComOp, gameComRd,
					gameChannel, gameNet, gameBBS, gameDown, image1Url, image2Url, image2Link, startTime, endTime,
					memo, introduce, adminId, rule);
			print(response, "1");
			//重定向到index页面
			return "redirect:/activity/index.do";
		} catch (Exception e) {
			e.printStackTrace();
			log.error("添加活动出错", e);
			print(response, "error:" + e.getMessage());
			return "redirect:/activity/toSavePage.do";
		}
	}

	/**
	 * 
	 * Description 去编辑活动信息页面
	 * @author lidongwei
	 * @since 2012-10-6
	 */
	@RequestMapping(value = "/toUpdatePage")
	public String toUpdatePage(Model model, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try {
			int faceStatus = getFaceStatus(request, model, activityService, "activityId");
			String activityId = StringUtils.trimToEmpty(request.getParameter("activityId"));
			if (faceStatus == 1 || faceStatus == 4) {
				//获取游戏列表和游戏类型列表
				List<NameValue> gameNameList = nameValueService.findNameValue(1);
				List<NameValue> gameTypeList = nameValueService.findNameValue(2);
				request.setAttribute("gameNameList", gameNameList);
				request.setAttribute("gameTypeList", gameTypeList);
				//获取id。根据id取得活动的详细信息

				Assert.hasText(activityId, "未获取活动id");
				Assert.isTrue(StringUtils.isNumeric(activityId), "获取活动id格式错误");
				Active active = activityService.findActivity(Integer.valueOf(activityId));
				model.addAttribute("active", active);
				//处理时间
				StringBuffer startDate = new StringBuffer();
				StringBuffer StartTime = new StringBuffer();
				getFrontDateTimeStr(active.getStartTime(), startDate, StartTime);

				StringBuffer endDate = new StringBuffer();
				StringBuffer endTime = new StringBuffer();

				getFrontDateTimeStr(active.getEndTime(), endDate, endTime);

				model.addAttribute("startDate", startDate.toString().trim());
				model.addAttribute("startHour", StartTime.toString().trim());
				model.addAttribute("endDate", endDate.toString().trim());
				model.addAttribute("endHour", endTime.toString().trim());

				return "activity/updateactivity";
			} else {
				throw new Exception("活动状态处于正在进行或已经结束，不能进行此操作");
			}
		} catch (Exception e) {
			log.error("进入修改页面出错", e);
			print(response, "error:" + e.getMessage());
			return null;
		}
	}

	/**
	 * 
	 * Description 保存修改后活动信息
	 * @author lidongwei
	 * @since 2012-10-6
	 */
	@RequestMapping(value = "/updateActivity")
	public String updateAdmin(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
		try {
			//获取页面信息
			int faceStatus = getFaceStatus(request, model, activityService, "activityid");
			if (faceStatus == 1 || faceStatus == 4) {
				String activeId = request.getParameter("activityid");
				String activeNmae = request.getParameter("activeName");
				String gameCode = request.getParameter("gameCode");
				String gameType = request.getParameter("gameType");
				String gameComOp = request.getParameter("gameComOp");
				String gameComRd = request.getParameter("gameComRd");
				String gameChannel = request.getParameter("gameChannel");
				String gameNet = request.getParameter("gameNet");
				String gameBBS = request.getParameter("gameBBS");
				String gameDown = request.getParameter("gameDown");
				String image1 = request.getParameter("image1Url");
				String image2 = request.getParameter("image2Url");
				String image2Link = request.getParameter("image2Link");
				String startDate = request.getParameter("startDate");
				String startHour = request.getParameter("startHour");
				String endDate = request.getParameter("endDate");
				String endHour = request.getParameter("endHour");
				String memo = request.getParameter("memo");
				String introduce = request.getParameter("introduceHtml");
				QiangbaAdmin admin = (QiangbaAdmin) request.getSession().getAttribute("loginedUser");

				String rule1Type = request.getParameter("baseinfo1Radio");
				String rule1Value = request.getParameter("baseinfo1Input");
				String rule1Memo = request.getParameter("baseinfo1Text");
				//断言进行判空：
				Assert.hasText(activeId, "不能获取活动id");
				Assert.isTrue(StringUtils.isNumeric(activeId), "活动id类型错误");
				Assert.hasText(image1, "不能获取上传文件地址");
				Assert.hasText(image2, "不能获取上传文件地址");
				Assert.hasText(image2Link, "图片链接不能为空");
				Assert.hasText(startDate, "开始日期不能为空");
				Assert.hasText(startHour, "开始时间不能为不能为空");
				Assert.hasText(endDate, "结束日期不能为不能为空");
				Assert.hasText(endHour, "结束时间不能为不能为空");
				Assert.hasText(memo, "活动描述不能为不能为空");
				Assert.hasText(introduce, "活动介绍不能为不能为空");
				Assert.notNull(admin, "活动添加人为空，请重新登录或联系管理员");

				//下面可为空
				String rule2Type = request.getParameter("baseinfo2Radio");
				String rule2Value = request.getParameter("baseinfo2Input");
				String rule2Memo = request.getParameter("baseinfo2Text");
				String rule3Type = request.getParameter("baseinfo3Radio");
				String rule3Value = request.getParameter("baseinfo3Input");
				String rule3Memo = request.getParameter("baseinfo3Text");
				//处理活动规则
				List<ActiveRule> arList = new ArrayList<ActiveRule>();
				if (rule1Type != null && rule1Type.length() != 0) {
					ActiveRule activeRule1 = new ActiveRule();
					activeRule1.setType(rule1Type);
					activeRule1.setMemo(rule1Memo);
					activeRule1.setValue(Integer.valueOf(rule1Value));
					arList.add(activeRule1);
				}

				if (rule2Type != null && rule2Type.length() != 0) {
					ActiveRule activeRule2 = new ActiveRule();
					activeRule2.setType(rule2Type);
					activeRule2.setMemo(rule2Memo);
					activeRule2.setValue(Integer.valueOf(rule2Value));
					arList.add(activeRule2);
				}
				if (rule3Type != null && rule3Type.length() != 0) {
					ActiveRule activeRule3 = new ActiveRule();
					activeRule3.setType(rule3Type);
					activeRule3.setMemo(rule3Memo);
					activeRule3.setValue(Integer.valueOf(rule3Value));
					arList.add(activeRule3);
				}

				//生成json串
				String rule = JacksonUtil.toJson(arList);
				//处理时间
				String startTime = getDateStr(startDate, startHour);
				String endTime = getDateStr(endDate, endHour);
				//处理gamecode、gameType
				String gameNmae = "";
				if (gameCode != null)
					gameNmae = nameValueService.findGameNameByGameCode(gameCode);//根据gamecode获取gamename
				if ("null".equals(gameType)) {
					gameType = "";
				}
				//写入数据库
				activityService.updateOneActivity(activeId, activeNmae, gameCode, gameNmae, gameType, gameComOp,
						gameComRd, gameChannel, gameNet, gameBBS, gameDown, image1, image2, image2Link, startTime,
						endTime, memo, introduce, rule);
				print(response, "1");
				//重定向到index页面
				return "redirect:/activity/index.do";
			} else {
				throw new Exception("活动状态处于正在进行或已经结束，不能进行此操作");
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("添加活动出错", e);
			print(response, "error:" + e.getMessage());
		}
		return null;
	}

	/**
	 * 
	 * Description 删除活动，ajax
	 * @author lidongwei
	 * @since 2012-10-6
	 */
	@RequestMapping(value = "/removeActivity")
	public String removeActivity(Model model, HttpServletRequest request, HttpServletResponse response)
			throws IOException {

		try {
			int faceStatus = getFaceStatus(request, model, activityService, "acId");
			String activityId = request.getParameter("acId");
			if (faceStatus == 1) {
				activityService.removeActivity(activityId);
				print(response, "1");
			} else {
				throw new Exception("活动状态处于正在进行或已经结束，不能进行此操作");
			}
		} catch (Exception e) {
			log.error("删除活动出错", e);
			print(response, "error:" + e.getMessage());
		}
		return null;
	}

	/**
	 * 
	 * Description 发布活动，ajax
	 * @author lidongwei
	 * @since 2012-10-6
	 */
	@RequestMapping(value = "/publishActivity")
	public String publishActivity(Model model, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try {
			int faceStatus = getFaceStatus(request, model, activityService, "acId");
			String activityId = request.getParameter("acId");
			if (faceStatus == 1 || faceStatus == 4) {
				activityService.updatePublishAcitivity(activityId);
				print(response, "1");
			} else {
				throw new Exception("活动状态处于正在进行或已经结束，不能进行此操作");
			}
		} catch (Exception e) {
			log.error("发布活动出错", e);
			print(response, "error:" + e.getMessage());
		}
		return null;
	}

	/**
	 * Description 从173的接口获取gamecode相对应的信息
	 * @author lidongwei
	 * @throws IOException 
	 * @since 2012-9-27
	 */
	@RequestMapping(value = "/getGameInfoJsonFrom173")
	public void getGameInfoJsonFrom173(HttpServletRequest request, HttpServletResponse response) throws IOException {
		try {
			String gameCode = request.getParameter("gameNameVar");
			Assert.hasText(gameCode, "未取得 gameCode ");
			GameInfo gameInfo;

			gameInfo = gameInfoService.getGameInfo(gameCode);
			if (gameInfo != null) {

				JSONArray jsonArray = new JSONArray();
				JSONObject jsonObject = new JSONObject();

				jsonObject.put("gameBBSLink", gameInfo.getGameBBSLink());
				jsonObject.put("gamecode", gameInfo.getGamecode());
				jsonObject.put("gameDeveloper", gameInfo.getGameDeveloper());
				jsonObject.put("gameDownLoadLink", gameInfo.getGameDownLoadLink());
				jsonObject.put("gameLink", gameInfo.getGameLink());
				jsonObject.put("gameName", gameInfo.getGameName());
				jsonObject.put("gameOperator", gameInfo.getGameOperator());
				jsonObject.put("gameType", gameInfo.getGameType());
				jsonObject.put("gameZoneLink", gameInfo.getGameZoneLink());
				jsonArray.put(jsonObject);

				response.getWriter().print(jsonArray);
			} else {
				print(response, "error:noGameInfo");//没有获取到数据的错误，不处理
			}
		} catch (JSONException e) {
			log.error("json构造出错", e);
			print(response, "error:" + e.getMessage());
		} catch (QbGetDataException e) {
			log.error("从173获取游戏信息出错", e);
			print(response, "error:" + e.getMessage());
		} catch (IOException e) {
			log.error("写入页面出错", e);
			print(response, "error:" + e.getMessage());
		}

	}

	/**
	 * 
	 * Description 关闭或开启活动
	 * @author lidongwei
	 * @since 2012-10-6
	 */
	@RequestMapping(value = "/closeOpenActivity")
	public String closeOpenActivity(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//获取id
		String activityId = request.getParameter("acId");
		Assert.hasText(activityId, "不能获取活动id");
		Assert.isTrue(StringUtils.isNumeric(activityId), "活动id类型错误");
		try {
			activityService.updateCloseOpenActivity(activityId);
			print(response, "1");
		} catch (Exception e) {
			log.error("关闭或开启活动出错", e);
			print(response, "error:" + e);
		}
		return null;

	}

	/**
	 * 
	 * Description 进行活动充值
	 * @author lidongwei
	 * @since 2012-10-6
	 */
	@RequestMapping(value = "/rechargeGold")
	public String rechargeGold(HttpServletRequest request, HttpServletResponse response, Model model)
			throws IOException {
		String accountNo = request.getParameter("accountNo");
		String accountPass = request.getParameter("accountPass");
		String rechargeMoney = request.getParameter("rechargeMoney");
		String acId = request.getParameter("acId");
		QiangbaAdmin admin = (QiangbaAdmin) request.getSession().getAttribute("loginedUser");
		//断言
		Assert.hasText(accountNo, "不能获取账号");
		Assert.hasText(accountPass, "不能获取密码");
		Assert.hasText(rechargeMoney, "不能获取充值金额");
		Assert.isTrue(StringUtils.isNumeric(rechargeMoney), "活动id类型错误，必须是整数");
		Assert.hasText(acId, "不能获取活动id");
		Assert.isTrue(StringUtils.isNumeric(acId), "活动id类型错误");
		Assert.notNull(admin, "未登录用户不能进行充值");
		try {
			int faceStatus = getFaceStatus(request, model, activityService, "acId");
			if (faceStatus == 1 || faceStatus == 4) {
				Active act = activityService.findActivity(Integer.valueOf(acId));
				if (act.getFaceNum() != -1) {//在173活动已经创建成功,所以使用追加充值
					int appFlag = qbOperateService.appendGb(accountNo, accountPass, act.getFaceNum(),
							Integer.valueOf(rechargeMoney), act.getMemo());
					if (1 == appFlag) {

						activityService.updateRechargeGold(acId, rechargeMoney, act.getFaceNum() + "",
								admin.getAdminId());
					} else if (0 == appFlag) {
						throw new Exception("充值失败");
					} else if (4 == appFlag) {
						throw new Exception("充值失败,余额不足");
					} else if (3 == appFlag) {
						throw new Exception("充值失败,参数不全");
					} else if (9 == appFlag) {
						throw new Exception("充值失败,IP不被允许");
					}
				} else {
					ActivityInfo info = new ActivityInfo();
					info.setQbId(act.getId().toString());
					info.setActClass("1");
					info.setActName(act.getActiveName());
					if (act.getGameCode() != null && !act.getGameCode().trim().equals("")) {
						info.setGamecode(Integer.valueOf(act.getGameCode().trim()));
					}
					info.setActStartTime(DateFormatUtils.format(act.getStartTime(), "yyyy-MM-dd"));
					info.setActEndTime(DateFormatUtils.format(act.getEndTime(),"yyyy-MM-dd"));
					info.setActMemo(act.getMemo());
					//			info.set
					ActReturn acr = qbOperateService.applyGb(accountNo, accountPass, Integer.valueOf(rechargeMoney),
							info);
					String flag = acr.getFlag();
					if (acr.getAccId() == null || acr.getAccId().equals("")) {//活动未创建成功
						if (flag.equals("0")) {
							throw new Exception("创建活动失败");
						} else if (flag.equals("3")) {
							throw new Exception("创建活动失败,参数不全");
						} else if (flag.equals("9")) {
							throw new Exception("创建活动失败,IP不被允许");
						}

					} else {
						if (flag.equals("1")) {
							//创建成功
							activityService.updateRechargeGold(acId, rechargeMoney, acr.getAccId(), admin.getAdminId());
						} else {
							activityService.updateRechargeGold(acId, "0", acr.getAccId(), admin.getAdminId());
							if (flag.equals("0")) {
								throw new Exception("充值失败");
							} else if (flag.equals("4")) {
								throw new Exception("充值失败,余额不足");
							} else if (flag.equals("3")) {
								throw new Exception("充值失败,参数不全");
							} else if (flag.equals("9")) {
								throw new Exception("充值失败,IP不被允许");
							}

						}

					}
				}

				print(response, "1");
			} else {
				throw new Exception("活动状态处于正在进行或已经结束，不能进行此操作");
			}
		} catch (Exception e) {
			log.error("活动充值出错", e);
			print(response, "error:" + e);
		}
		return null;
	}

	/**
	 * 碎片帮助页面
	 * Description
	 * @author lidongwei
	 * @since 2012-10-30
	 */
	@RequestMapping(value = "/fragHelp")
	public String fragHelp(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "activity/activefragmenthelp";
	}

	/**
	 * 
	 * Description ajax上传图片
	 * @author lidongwei
	 * @since 2012-10-6
	 */

	@RequestMapping(value = "/ajaxUpload")
	public String ajaxUpload(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
		try {
			MultipartHttpServletRequest Multirequest = (MultipartHttpServletRequest) request;
			MultipartFile image1 = (MultipartFile) Multirequest.getFile("image1");
			MultipartFile image2 = (MultipartFile) Multirequest.getFile("image2");
			if (image1 != null) {
				if (image1.getBytes().length > Integer.valueOf(Constants.UPLOAD_FILE_SIZE_MAX)) {
					throw new RuntimeException("文件大小不能超过"+Integer.valueOf(Constants.UPLOAD_FILE_SIZE_MAX) / 1024+"k");
				}
				try {
					String visitUrl = uploadService.uploadFile(image1.getBytes(), image1.getOriginalFilename(),
							Integer.valueOf(Constants.UPLOAD_FILE_SIZE_MAX) / 1024);
					print(response, visitUrl);
					return null;
				} catch (Exception e) {
					e.printStackTrace();
					log.error("上传出错", e);
					print(response, "error:" + e.getMessage());
				}
			} else if (image2 != null) {
				if (image2.getBytes().length > Integer.valueOf(Constants.UPLOAD_FILE_SIZE_MAX)) {
					throw new RuntimeException("文件大小不能超过"+Integer.valueOf(Constants.UPLOAD_FILE_SIZE_MAX) / 1024+"k");
				}
				try {
					String visitUrl = uploadService.uploadFile(image2.getBytes(), image2.getOriginalFilename(),
							Integer.valueOf(Constants.UPLOAD_FILE_SIZE_MAX) / 1024);
					print(response, visitUrl);
					return null;
				} catch (Exception e) {
					e.printStackTrace();
					log.error("上传出错", e);
					print(response, "error:" + e.getMessage());
				}
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("上传出错", e);
			print(response, "error:" + e.getMessage());
		}
		return null;
	}

	/**
	 * 
	 * Description 根据页面填入的dateStr来形成标准格式的时间字符串
	 * @author lidongwei
	 * @since 2012-10-6
	 */
	private String getDateStr(String date, String time) throws Exception {
		//FIXME  去掉 繁琐的时间设置
		String tims[] = time.split(" ");
		String re = "";
		if (tims != null && tims.length > 0) {
			if ("PM".equalsIgnoreCase(tims[1])) {
				String littletims[] = tims[0].split(":");
				tims[0] = (Integer.valueOf(littletims[0]) + 12) + ":" + littletims[1] + "";
			}
			tims[0] = tims[0] + ":00";
			if (tims[0].length() < 8) {//处理times位数不为两位的情况，将7:00:00变为07:00:00
				tims[0] = "0" + tims[0];
			}
			re = date + " " + tims[0]; //转换为yyyy-MM-dd HH:mm:ss 的形式

		}
		return re;
	}

	/**
	 * 
	 * Description 根据数据库中获取的时间形成可在页面显示的字符串
	 * @author lidongwei
	 * @since 2012-10-6
	 */
	private void getFrontDateTimeStr(Date dateTime, StringBuffer date, StringBuffer time) {

		SimpleDateFormat tsdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String formattedDate = tsdf.format(dateTime);
		String[] dt = formattedDate.split(" ");
		date = date.append(dt[0]);
		String[] t = dt[1].split(":");

		if (Integer.valueOf(t[0]) > 12) {
			t[0] = (Integer.valueOf(t[0]) - 12) + "";
			time = time.append(t[0] + ":" + t[1] + " PM");
		} else if (Integer.valueOf(t[0]) < 10) {
			t[0] = String.valueOf(t[0].charAt(1));
			time = time.append(t[0] + ":" + t[1] + " AM");
		} else {
			time = time.append(t[0] + ":" + t[1] + " AM");
		}

	}

}
